package com.kye.express.business.update;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Environment;

import com.allenliu.versionchecklib.core.AVersionService;
import com.allenliu.versionchecklib.core.VersionParams;
import com.kye.express.R;
import com.kye.express.utils.NetUtils;
import com.kye.express.view.ToastManager;
import com.kye.model.ApiBase;
import com.kye.model.SharedPreferencesConfig;
import com.kye.model.SharedPreferencesManager;
import com.kye.model.UserSession;
import com.kye.model.bean.update.AppInfoBean;

import java.io.File;

public class UpdateService extends AVersionService {
    private static final String KYE_UPDATE_APK = "KYE_UPDATE_APK";

    public static String getDownloadApkCachePath() {
        String appCachePath;

        if (checkSDCard()) {
            appCachePath = Environment.getExternalStorageDirectory() + "/" + KYE_UPDATE_APK + "/";
        } else {
            appCachePath = Environment.getDataDirectory().getPath() + "/" + KYE_UPDATE_APK + "/";
        }
        File file = new File(appCachePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        return appCachePath;
    }

    public static boolean checkSDCard() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    public static void stopService(Context context) {
        context.stopService(new Intent(context, UpdateService.class));
    }

    @Override
    public void onResponses(AVersionService service, String response) {
        AppInfoBean appInfoBean;
        try {
            appInfoBean = ApiBase.getInstance().getGson().fromJson(response, AppInfoBean.class);
        } catch (Throwable throwable) {
            ToastManager.show(this, "返回数据错误");
            return;
        }

        SharedPreferencesManager.commit(SharedPreferencesConfig.KEY_IS_CAN_INTER_SHOP, appInfoBean.isCanInterShop());

        if (updateAvailable(appInfoBean)) {
            //判断版本之后在设置是否强制更新或者VersionParams
            CustomVersionDialogActivity.isForceUpdate = appInfoBean.isForceup();
            versionParams = new VersionParams.Builder()
                    .setDownloadAPKPath(versionParams.getDownloadAPKPath())
                    .setPauseRequestTime(versionParams.getPauseRequestTime())
                    .setRequestMethod(versionParams.getRequestMethod())
                    .setCustomDownloadActivityClass(versionParams.getCustomDownloadActivityClass())
                    .setForceRedownload(versionParams.isForceRedownload())
                    .setSilentDownload(NetUtils.isWifi(this))
                    .setOnlyDownload(versionParams.isOnlyDownload())
                    .setShowDownLoadFailDialog(versionParams.isShowDownloadFailDialog())
                    .setService(versionParams.getService())
                    .setShowNotification(versionParams.isShowNotification())
                    .setShowDownloadingDialog(versionParams.isShowDownloadingDialog())
                    .build();

            if (AppInfoBean.INNER.equals(appInfoBean.getUptype())) {
                // TODO 检测是否员工
                if (!UserSession.getInstance().getUser().isEmployee()) return;

                showVersionDialog(appInfoBean.getDownload(), getString(R.string.update_new_version), appInfoBean.getMsg());
            } else {
                showVersionDialog(appInfoBean.getDownload(), getString(R.string.update_new_version), appInfoBean.getMsg());
            }
        }
    }

    public boolean updateAvailable(AppInfoBean appInfoBean) {
        if (appInfoBean == null) return false;
        try {
            int versionCode = getPackageManager()
                    .getPackageInfo(getPackageName(), PackageManager.GET_META_DATA)
                    .versionCode;

            if (appInfoBean.getVersioncode() > versionCode) return true;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return false;
    }
}
